package client;

import java.io.*;
import java.net.*;

import eclMain.ChatLine;
import eclMain.Notifier;

/**Everything that pertains to communicating with the ECM server should be put here*/
public class ECMClient {
	
	private boolean liveConnection = false;
	private PrintWriter outbound = null;
	private BufferedReader in = null;
	private Socket ECMSocket = null;
	private int socketNum = 4444;
	private String serverName = "www.rivetingcode.net";
	
    public ECMClient() {
        startConnection(this.serverName, this.socketNum);
    }
    
    /**Sets up the connection to the ECM server*/
    public void startConnection(String serverName, int socketNum) {
        try {
            this.ECMSocket = new Socket(serverName, socketNum);
            this.outbound = new PrintWriter(this.ECMSocket.getOutputStream(), true);
            this.in = new BufferedReader(new InputStreamReader(this.ECMSocket.getInputStream()));
        } catch (UnknownHostException e) {
            Notifier.errorNotify("Unable to find host: " + serverName);
            System.exit(1);
        } catch (IOException e) {
            Notifier.errorNotify("Couldn't get I/O for the connection to: " + serverName);
            System.exit(1);
        }
        Notifier.standardNotify("Connected to server: " + this.serverName);
        this.liveConnection = true;
        monitorServerComm();
    }
    
    /**Monitors all incoming communications from the server. Works on it's own thread.*/
    public void monitorServerComm() {
    	Thread thread = new Thread(new Runnable() {	
			@Override
			public void run() {
				String fromServer = "";
				try {
					while (fromServer != null && fromServer != "terminated") {
						fromServer = in.readLine();
						System.out.println(fromServer);
					}
					outbound.close();
					in.close();
					ECMSocket.close();
				} catch(Exception e) {
					Notifier.errorNotify("Lost Connection to ECM Server");
				} finally {
					liveConnection = false;
				}
			}
		});
    	thread.start();
    }
    
    public void send(ChatLine line) {
    	if (this.liveConnection == false) {
    		startConnection(this.serverName, this.socketNum);
    	}
    	String pl = line.processOutput();
    	this.outbound.println(pl);
    }
}